package com.yueya.basic.dept.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yueya.basic.dept.model.Dept;
import com.yueya.basic.dept.model.DeptBase;
import com.yueya.common.model.Tree;
import com.yueya.common.service.BaseService;
import com.yueya.common.util.DateUtil;
import com.yueya.common.util.UUIDGenerator;

public class DeptService extends BaseService {

	public DeptBase getDeptExtByDeptId(String deptId) {
		String sql = "select * from t_dept_base where dept_id = '" + deptId
				+ "'";
		return DeptBase.dao.findFirst(sql);
	}

	public List<Dept> getDeptsByParentId(String pid) {
		String sql = "select * from t_dept where dept_parent_id = '" + pid
				+ "' and del_flag = '0' order by order_id asc";
		return Dept.dao.find(sql);
	}

	public int getDeptNumByParentId(String pid) {
		String sql = "select dept_id from t_dept where dept_parent_id = '" + pid
				+ "' and del_flag = '0'";
		List<Record> list = Db.find(sql);
		if (list != null && list.size() > 0) {
			return list.size();
		}
		return 0;
	}

	public Page<Record> pagination(int pageNumber, int pageSize,
			Map<String, Object> map) {

		String select = "select d.*,i.dept_name as parent_name ";
		StringBuffer sb = new StringBuffer(
				" from t_dept d left join t_dept i on i.dept_id=d.dept_parent_id where d.del_flag = '0' and d.dept_id!='000'  ");

		if (!"".equals(map.get("d.dept_level"))
				&& map.get("d.dept_level") != null) {
			sb.append(" and d.dept_level = " + map.get("d.dept_level"));
		}

		if (!"".equals(map.get("parentid")) && map.get("parentid") != null) {
			sb.append(" and d.dept_parent_id = '" + map.get("parentid") + "'");
		}
		if (!"".equals(map.get("sid")) && map.get("sid") != null) {
			sb.append(" or d.dept_id = '" + map.get("sid") + "'");
		}
		if (!"".equals(map.get("name")) && map.get("name") != null) {
			sb.append(" and  d.dept_name like '%" + map.get("name") + "%'");
		}

		if (map.get("order_name") != null) {
			sb.append(" order by d." + map.get("order_name") + " "
					+ map.get("order"));
		} else {
			sb.append(" order by d.order_id asc,d.create_time asc");
		}

		String sql = sb.toString();
		Page<Record> page = Db.paginate(pageNumber, pageSize, select, sql);

		return page;

	}

	@Before(Tx.class)
	public boolean save(Dept dept, DeptBase deptBase) {
		boolean bl = false;
		String id = dept.getStr("dept_id");
		String currentDate = DateUtil.getDate(DateUtil.timeFormat);
		if (id == null) {
			id = UUIDGenerator.getUUID();
			dept.set("dept_id", id);
			dept.set("create_time", currentDate);
			int maxOrderId = getMaxOrder(dept.getStr("dept_parent_id"));
			int parentDeptLevel = getLevel(dept.getStr("dept_parent_id"));
			dept.set("order_id", maxOrderId + 1);
			dept.set("dept_level", parentDeptLevel + 1);
			bl = dept.save();
			if (!bl) {
				return bl;
			}

			deptBase.set("dept_id", id);
			deptBase.set("dept_base_id", UUIDGenerator.getUUID());
			bl = deptBase.save();
			if (!bl) {
				return bl;
			}
		} else {
			dept.set("update_time", currentDate);
			int parentDeptLevel = getLevel(dept.getStr("dept_parent_id"));
			dept.set("dept_level", parentDeptLevel + 1);
			bl = dept.update();
			if (!bl) {
				return bl;
			}

			String idbase = deptBase.getStr("dept_base_id");
			if (idbase != null) {
				bl = deptBase.update();
				if (!bl) {
					return bl;
				}
			}
		}

		return bl;
	}

	public int getMaxOrder(String pid) {
		String sql = "select MAX(order_id) as max_order_id from t_dept where dept_parent_id = '"
				+ pid + "'";
		Dept dept = Dept.dao.findFirst(sql);
		int max = 0;
		if (dept.get("max_order_id") != null) {
			// max = dept.getBigDecimal("max_order_id").intValue();
			max = dept.getInt("max_order_id");
		}

		return max;
	}

	public int getLevel(String pid) {
		String sql = "select MAX(dept_level) as dept_level from t_dept where dept_id = '"
				+ pid + "'";
		Dept dept = Dept.dao.findFirst(sql);
		int max = 0;
		if (dept.get("dept_level") != null) {
			// max = dept.getBigDecimal("max_order_id").intValue();
			max = dept.getInt("dept_level");
		}

		return max;
	}

	public List<Dept> getAllDept() {
		String sql = "select * from t_dept where dept_status = '1' and del_flag = '0' order by order_id asc";
		return Dept.dao.find(sql);
	}

	public List<Dept> childList() {
		String sql = " select * from t_dept where dept_parent_id != 0 ";
		List<Dept> list = Dept.dao.find(sql);
		return list;
	}

	/**
	 * 所属的部门
	 * 
	 * @param parend_id
	 * @return
	 */
	public List<Dept> _rt(String parend_id, int level) {
		List<Dept> r = null;
		String sql = " select  * from  t_dept  where  dept_parent_id = ? order by order_id asc";
		r = Dept.dao.find(sql, parend_id);
		return r;
	}

	/**
	 * 此功能实现将数据menu 转化为 tree 格式
	 * 
	 * @param list
	 * @return
	 */
	public List<Tree> toTreeList(List<Dept> list) {
		Iterator<Dept> it = list.iterator();
		List<Tree> treeList = new ArrayList<Tree>();
		while (it.hasNext()) {
			Tree tr = new Tree();
			Dept mu = it.next();
			tr.setId(mu.getStr("dept_id"));
			tr.setState("closed");

			if (isleaf(mu.getStr("dept_id"))) {
				tr.setState("open");
			} else {
				tr.setState("closed");

			}

			if ("0".equals(mu.getStr("dept_parent_id"))) {
				tr.setIconCls("icon-wlkj-organ");
			} else {
				tr.setIconCls("icon-wlkj-dept");
			}
			// tr.setChecked(true);
			// tr.setLevel(mu.getInt("dept_level"));
			tr.setPid(mu.getStr("dept_parent_id"));
			tr.setAttributes(mu);
			tr.setText(mu.getStr("dept_name"));
			treeList.add(tr);
		}

		return treeList;
	}

	public List<Tree> toTreeList(List<Dept> list, String str) {
		Iterator<Dept> it = list.iterator();
		List<Tree> treeList = new ArrayList<Tree>();
		while (it.hasNext()) {
			Tree tr = new Tree();
			Dept mu = it.next();
			tr.setId(mu.getStr("dept_id"));
			tr.setState("open");
			if ("0".equals(mu.getStr("dept_parent_id"))) {
				tr.setIconCls("icon-wlkj-organ");
			} else {
				tr.setIconCls("icon-wlkj-dept");
			}
			// tr.setChecked(true);
			// tr.setLevel(mu.getInt("dept_level"));
			tr.setPid(mu.getStr("dept_parent_id"));
			// tr.setAttributes(mu);
			tr.setText(mu.getStr("dept_name"));
			treeList.add(tr);
		}

		return treeList;
	}


	public List<Tree> toTreeList4(List<Record> list) {

		Iterator<Record> it = list.iterator();
		List<Tree> treeList = new ArrayList<Tree>();
		while (it.hasNext()) {
			Tree tr = new Tree();
			Record mu = it.next();
			tr.setId(mu.getStr("dept_id"));
			tr.setState("closed");
			tr.setState("open");
			tr.setIconCls("icon-sy02");
			// tr.setChecked(true);
			tr.setPid(mu.getStr("dept_id"));
			tr.setAttributes(mu);
			tr.setText(mu.getStr("user_name"));
			treeList.add(tr);
		}

		return treeList;

	}

	public boolean isleaf(String pid) {

		return getDeptNumByParentId(pid) == 0;
	}

	public List<Tree> toTreeList2(List<Dept> list, String status) {
		Iterator<Dept> it = list.iterator();
		List<Tree> treeList = new ArrayList<Tree>();
		while (it.hasNext()) {
			Dept mu = it.next();
			if (Dept.dao.isleaf2(mu.getStr("dept_id"))) {
				Tree tr = new Tree();
				tr.setId(mu.getStr("dept_id"));
				tr.setState(status);
				if ("0".equals(mu.getStr("dept_parent_id"))) {
					tr.setIconCls("icon-wlkj-organ");
				} else {
					tr.setIconCls("icon-wlkj-dept");
				}
				// tr.setChecked(false);
				// tr.setLevel(mu.getInt("dept_level"));
				tr.setPid(mu.getStr("dept_parent_id"));
				// tr.setAttributes(mu);
				tr.setText(mu.getStr("dept_name"));
				treeList.add(tr);
			}
		}

		return treeList;
	}

	public List<Tree> splitTree(List<Tree> rt, List<Tree> bh, List<Tree> bh2) {

		Dept.dao.bf(bh, bh2);// batch+batch2
		Dept.dao.bf(rt, bh);// root+batch
		return rt;
	}

	public List<Record> getDeptByType(String type) {
		String sql = "select * from t_dept where dept_status = '1' and del_flag = '0' and dept_type = '"
				+ type + "' order by order_id asc";
		return Db.find(sql);

	}

	public List<Tree> splitTreeU(List<Tree> rt, List<Tree> bh, List<Tree> bh2) {

		Dept.dao.bf2(bh, bh2);// batch+batch2
		Dept.dao.bf(rt, bh);// root+batch
		return rt;
	}

	public Tree getTreeNode(String cid) {
		Dept category = Dept.dao
				.findFirst(" select dept_id,dept_name,dept_parent_id from  t_dept where dept_id = '"
						+ cid + "' ");
		Tree root = new Tree();
		root.setId(category.getStr("dept_id"));
		if (cid == "000") {
			root.setIconCls("icon-wlkj-organ");
		} else {
			root.setIconCls("icon-wlkj-dept");
			if (Dept.service.isleaf(cid)) {
				root.setState("open");
			} else {
				root.setState("closed");
			}

		}

		root.setPid(category.getStr("dept_parent_id"));
		root.setText(category.getStr("dept_name"));

		return root;
	}

	public List<Tree> queryTreeNode(String pid) {
		List<Dept> list = Dept.dao
				.find(" select dept_id,dept_name,dept_parent_id from  t_dept where del_flag='0' and dept_parent_id = '"
						+ pid + "' order by order_id asc");
		List<Tree> treeList = null;
		Tree root = null;
		Dept d = null;
		if (list != null && list.size() > 0) {
			treeList = new ArrayList<Tree>();
			for (int i = 0; i < list.size(); i++) {
				root = new Tree();
				d = list.get(i);
				root.setId(d.getStr("dept_id"));
				root.setIconCls("icon-wlkj-dept");
				root.setPid(d.getStr("dept_parent_id"));
				root.setText(d.getStr("dept_name"));
				treeList.add(root);
			}
		}

		return treeList;
	}

	public List<Tree> queryTreeNode(String pid, List<String> listdept) {
		List<Dept> list = Dept.dao
				.find(" select dept_id,dept_name,dept_parent_id from  t_dept where del_flag='0' and dept_parent_id = '"
						+ pid + "' order by order_id asc");
		List<Tree> treeList = null;
		Tree root = null;
		Dept d = null;
		if (list != null && list.size() > 0) {
			treeList = new ArrayList<Tree>();
			for (int i = 0; i < list.size(); i++) {
				root = new Tree();
				d = (Dept) list.get(i);
				root.setId(d.getStr("dept_id"));
				root.setIconCls("icon-wlkj-dept");
				root.setPid(d.getStr("dept_parent_id"));
				root.setText(d.getStr("dept_name"));
				for (int j = 0; j < listdept.size(); j++) {
					if (listdept.get(j).equals(root.getId())) {
						root.setChecked(true);
						break;
					}
				}

				treeList.add(root);
			}
		}

		return treeList;
	}

	public Tree recursiveTree(String cid) {
		// 根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?)
		Tree node = getTreeNode(cid);
		// 查询cid下的所有子节点(SELECT * FROM tb_tree t WHERE t.pid=?)
		List<Tree> childTreeNodes = queryTreeNode(cid);
		// System.out.print(childTreeNodes.size());
		// 遍历子节点
		if (childTreeNodes != null && childTreeNodes.size() > 0) {
			for (Tree child : childTreeNodes) {

				Tree n = recursiveTree(child.getId()); // 递归
				node.getChildren().add(n);

			}
		}

		return node;
	}

	public Tree recursiveTree(String cid, List<String> listdept) {
		// 根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?)
		Tree node = getTreeNode(cid);
		// 查询cid下的所有子节点(SELECT * FROM tb_tree t WHERE t.pid=?)
		List<Tree> childTreeNodes = queryTreeNode(cid, listdept);
		// System.out.print(childTreeNodes.size());
		// 遍历子节点
		if (childTreeNodes != null && childTreeNodes.size() > 0) {
			for (Tree child : childTreeNodes) {

				Tree n = recursiveTree(child.getId()); // 递归
				for (int i = 0; i < listdept.size(); i++) {
					if (listdept.get(i).equals(n.getId())) {
						n.setChecked(true);
						break;
					}
				}

				node.getChildren().add(n);

			}
		}

		return node;
	}

}
